import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';
const env = import.meta.env;

class Request {
    constructor(timeout = 5000) {
        this.baseUrl = env.VITE_API_URL;
        this.instance = axios.create({
            baseURL: this.baseUrl,
            headers: {
                'Content-Type': 'application/json',
            },
            timeout: timeout, // 设置超时时间
        });

        this.instance.interceptors.request.use(config => {
            config.loadingInstance = ElLoading.service({
                lock: true,
                text: '加载中...',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            return config;
        });

        this.instance.interceptors.response.use(
            response => {
                if (response.config.loadingInstance) {
                    response.config.loadingInstance.close();
                }
                return response;
            },
            error => {
                if (error.config && error.config.loadingInstance) {
                    error.config.loadingInstance.close();
                }
                if (error.code === 'ECONNABORTED') {
                    ElMessage.error('请求超时，请稍后重试');
                }
                return Promise.reject(error);
            }
        );
    }

    async get(url, params = {}) {
        try {
            const response = await this.instance.get(url, { params });
            return response.data;
        } catch (error) {
            this.handleError(error);
        }
    }

    async post(url, data = {}) {
        let token = localStorage.getItem('token');

        try {
            const headers = token ? { Authorization: `${token}` } : {};
            const response = await this.instance.post(url, data, { headers });
            let result = response.data;
            if (result.code === 301) {
                ElMessage.error(result.message);
                localStorage.removeItem('token');
                // window.location.href = '/login';
            }

            return result;
        } catch (error) {
            ElMessage.error('请求失败，请重试');
            this.handleError(error);
        }
    }

    handleError(error) {
        console.error('API call error:', error);
        throw error;
    }
}

export default Request;
